<template>
  <div class="fileupload-page">
    <div>
      <a-upload-dragger
        :multiple="true"
        action="https://gitee.com/api/v5/repos/TimeOfPassage/gfile/contents/"
        @change="handleChange"
        :customRequest="onCustomUpload"
      >
        <p class="ant-upload-drag-icon">
          <a-icon type="inbox" />
        </p>
        <p class="ant-upload-text">
          点击选择文件上传或拖拽文件到此区域进行上传
        </p>
        <p class="ant-upload-hint">
          支持单文件上传或批量文件上传,重要文件请酌情考虑是否上传.
        </p>
      </a-upload-dragger>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import axios from "axios";
import { Upload } from "ant-design-vue";
Vue.use(Upload);
// 获取文件base64信息
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
export default {
  name: "FileUpload",
  data() {
    return {};
  },
  methods: {
    handleChange(info) {
      const status = info.file.status;
      if (status !== "uploading") {
        console.log(info.file, info.fileList);
      }
      if (status === "done") {
        this.$message.success(`${info.file.name} file uploaded successfully.`);
      } else if (status === "error") {
        this.$message.error(`${info.file.name} file upload failed.`);
      }
    },
    async onCustomUpload(req) {
      //   console.log(req);
      let url = req.action + req.file.name;
      let filename = req.file.name;
      let fileBase64Info = await getBase64(req.file);
      if (fileBase64Info) {
        fileBase64Info = fileBase64Info.substr(
          fileBase64Info.indexOf("base64,") + 7
        );
      }
      return this.uploadFile(url, req.file, filename, fileBase64Info);
    },
    uploadFile(url, file, filename, fileBase64Info) {
      // 发送 POST 请求
      axios({
        method: "post",
        url: url,
        data: {
          message: "commit file: " + filename,
          access_token: "f56515355a71b8a27e6b6682ca5440ae",
          content: fileBase64Info,
        },
      }).then(function (response) {
        console.log(response.data);
        console.log(response.status);
        console.log(response.statusText);
        console.log(response.headers);
        console.log(response.config);
        // this.$message.success("文件上传成功！");
        file.status = "done";
        return file;
      });
    },
  },
};
</script>

<style>
.fileupload-page {
  max-width: 100%;
  height: 100%;
  overflow-y: auto;
}

.fileupload-page > div {
  height: 95%;
  padding: 5px;
}

.fileupload-page .ant-upload-list {
  margin-bottom: 20px;
}
</style>